package com.itheima.tlias.web.interceptors;

import com.alibaba.fastjson.JSON;
import com.itheima.tlias.utils.JwtUtils;
import com.itheima.tlias.vo.Result;
import com.mysql.cj.util.StringUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ghy
 * @version 1.0.1
 * @date 2024-01-30 14:35:53
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static final String TOKEN = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        // 1.获取token
        String token = request.getHeader(TOKEN);
        // 2.判断token是否为空
        if(StringUtils.isNullOrEmpty(token)) {
            log.error("token为空");
            // 3.为空或者为“”，拦截，响应数据
            String json = JSON.toJSONString(Result.error("NOT_LOGIN"));
            response.getWriter().write(json);
            return false;
        }
        // 4.不为空，验证token
        try {
            Claims claims = JwtUtils.parseJwt(token);
            log.info("token验证通过");
            System.out.println(claims);
        } catch (Exception e) {
            log.error("非法token");
            //e.printStackTrace();
            // 5.验证失败，拦截，响应数据
            String json = JSON.toJSONString(Result.error(e.getMessage() + "-->中文测试"));
            response.getWriter().write(json);
            return false;
        }
        // 6.验证成功，放行
        return true;
    }
}
